/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tickets.tickets;

import tickets.ticketRegister.TicketRegister;
import tickets.timingService.TimingService;
import java.util.Date;
import tickets.passageRegister.PassageRegister;

/**
 * Class that is scanning tickets
 * 
 * @author Hlib_Babii
 */
public class Turnstile {
    
    private TicketRegister ticketRegister;
    
    private PassageRegister passageRegister;
    
    private TimingService timingService;
    
    Turnstile(TicketRegister ticketRegister, PassageRegister passageRegister
                ,TimingService timingService) {
        this.passageRegister = passageRegister;
        this.ticketRegister = ticketRegister;
        this.timingService = timingService;
    }
    
    public TicketRegister getTicketRegister() {
        return ticketRegister;
    }

    public void setTicketRegister(TicketRegister ticketRegister) {
        this.ticketRegister = ticketRegister;
    }

    public PassageRegister getPassageRegister() {
        return passageRegister;
    }

    public void setPassageRegister(PassageRegister passageRegister) {
        this.passageRegister = passageRegister;
    }

    public TimingService getTimingService() {
        return timingService;
    }

    public void setTimingService(TimingService timingService) {
        this.timingService = timingService;
    }
    
    /**
     * 
     * @param ticketId id of the scanned ticket
     * @return {@code Passage} object that is result of scanning
     */
    public Passage applyTicket(long ticketId) {
        Passage passage = pass(ticketId);
        passageRegister.addPassage(passage);
        return passage;
    }

    private Passage pass(long ticketId) {
        Ticket ticket = ticketRegister.getTicketById(ticketId);
        Passage passage;
        if (ticket != null) {
            PassageState passageState = ticket.check();
            if (passageState.passageAllowed()) {
                ticket.use();
            }
            passage = new Passage(ticket, timingService.getCurrentTime(), passageState);
        } else {
            passage = new Passage(null, timingService.getCurrentTime(), PassageState.FAKE_TICKET);
        }
        return passage;
    }
}
